package bakenote.xml;

import bakenote.core.ElementalProcedure;
import bakenote.core.Procedure;
import org.apache.pivot.serialization.SerializationException;
import org.apache.pivot.xml.Element;
import org.apache.pivot.xml.XMLSerializer;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * ;* User: lello
 * Date: 4/29/11
 * Time: 9:32 PM
 */
public class ProcedureXMLReader {

    private ProcedureXMLReader() {
        // No-op
    }

    public static Procedure readXML(File xmlFile) {

        Procedure procedure = new Procedure();
        XMLSerializer xmlSerializer = new XMLSerializer();
        try {
            System.out.println("reading procedure file"+xmlFile);
            FileInputStream fileInputStream = new FileInputStream(xmlFile);
            Element element = xmlSerializer.readObject(fileInputStream);
            for (Element e : element.getElements("step")) {
                ElementalProcedure elementalProcedure = new ElementalProcedure();
                Element timeElement = e.getElements("time").get(0);
                try {
                    elementalProcedure.setDuration(DatatypeFactory.newInstance().newDuration(timeElement.getText()));
                } catch (DatatypeConfigurationException e1) {
                    System.out.println("cannot parse duration " + timeElement.getText());
                }
                Element descriptionElement = e.getElements("description").get(0);
                elementalProcedure.setDescription(descriptionElement.getText());
                //System.out.println(" title "+titleElement.getText());
                procedure.add(elementalProcedure);
            }
        } catch (FileNotFoundException e) {
            System.out.println("Cannot find procedure file");
            //e.printStackTrace();
        } catch (SerializationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return procedure;
    }
}
